//LiuZh 2017-06-27
import React, {Component} from 'react';

import {
    View,
    Image,
    Dimensions,
    TouchableWithoutFeedback,
    StyleSheet,
    Text,
    TouchableOpacity,
    TextInput,
    KeyboardAvoidingView,
    ScrollView
} from 'react-native';

import {NavigationActions} from 'react-navigation'
import {connect} from 'react-redux'
import Loading from '../../core/component/comp.global-loading';

const SmartKeyboard = require('@remobile/react-native-smart-keyboard');
var dismissKeyboard = require('dismissKeyboard');
import Util from '../utils/util';
import InitDB from '../database/init-db';
import Color from '../constant/color';

import {userActions} from '../../actions';

import Constant from '../constant/constant';

let winWidth = Dimensions.get('window').width;//屏幕宽度
let winHeight = Dimensions.get('window').height;//屏幕宽度


class LoginScene extends Component {
    constructor(props) {
        super(props);
        this.state = {
            showGlobalLoading: false,
            username: '',
            password: '',
            loginButton_disabled: false,
            loginButton_bgColor: Constant.loginButton_enable_bgColor,
            loginButtonTxtColor: Constant.loginButton_enable_txtColor,
            loading: false,
            ll: false,
        }
    }


    componentWillUnmount() {
        Util.hiddenGlobalLoading(this)
    }


    componentDidMount() {
        /*
        this.props.navigation.navigate("ResetPwd",{
            username_new:'18310546021',
            yanzhengma:'111111',
        })

       this.props.navigation.navigate("UpdateMobile2", {
           username_new:'18310546021',
           yanzhengma:'111111',
       })

       this.props.navigation.navigate("Register2", {
           mobile: 18101325837,
           password: '11111111',
           operateType: 'add'
       })

        */

    }

    genPageTitleUI() {
        return (
            <View style={styles.header}>
                <Text style={{fontSize: 24}}>手机号登陆</Text>
            </View>
        );
    }

    genPhoneNumberInputUI() {
        return (
            <View style={styles.inputBox}>
                <Image style={styles.icon}
                       resizeMode={'contain'}
                       source={require('../../img/login_user.png')}/>
                <TextInput style={styles.inputText}
                           placeholder={'手机号码'}
                           placeholderTextColor={'#CCC'}
                           underlineColorAndroid="transparent"
                           autoCapitalize="none"
                           autoCorrect={false}
                           blurOnSubmit={true}
                           onChangeText={(text) => {
                               this.setState({username: text});
                           }}/>
            </View>
        );
    }

    genPasswordInputUI() {
        return (
            <View style={styles.inputBox}>
                <Image style={[styles.icon, {height: 17}]}
                       source={require('../../img/login_pwd.png')}/>
                <TextInput style={styles.inputText}
                           secureTextEntry={true}
                           placeholder={'密码'}
                           blurOnSubmit={true}
                           placeholderTextColor={'#CCC'}
                           underlineColorAndroid="transparent"
                           onChangeText={(text) => {
                               this.setState({password: text})
                           }}/>
            </View>
        );
    }

    genForgetPasswordPanelUI() {
        return (
            <View style={styles.pwdBox}>
                <View style={{flex: 1,}}/>
                <TouchableWithoutFeedback onPress={this.forgetPassword}>
                    <View>
                        <Text style={styles.hintText}>忘记密码</Text>
                    </View>
                </TouchableWithoutFeedback>
            </View>
        );
    }

    genLoginBtn() {
        return (
            <TouchableOpacity style={styles.btn_login}
                              disabled={this.state.loginButton_disabled}
                              activeOpacity={0.6} onPress={this.onPressSubmit}>
                <Text style={styles.btn_text}>登 录</Text>
            </TouchableOpacity>
        );
    }

    genRegisterBtn() {
        return (
            <TouchableWithoutFeedback
                onPress={() => {
                    this.props.navigation.navigate('Register1')
                }}>
                <View>
                    <Text style={[styles.hintText, {
                        color: Color.TEXT_HREF,
                        alignSelf: 'center',
                        marginTop: 20
                    }]}>新用户注册</Text>
                </View>
            </TouchableWithoutFeedback>
        );xiangyue
    }

    genAgreementUI() {
        return (
            <View style={{
                top: winHeight - 40,
                left: winWidth / 2 - 100,
                justifyContent: "center",
                position: "absolute"
            }}>
                <TouchableOpacity onPress={() => {
                    this.props.navigation.navigate('UserXieyi')
                }}>
                    <Text style={{fontSize: 12}}>登陆即表示同意<Text
                        style={{color: Color.TEXT_STRESS}}>《享约-用户协议》</Text></Text>
                </TouchableOpacity>
            </View>
        );
    }

    render() {
        return (
            <ScrollView style={styles.body}>
                <Loading show={this.state.showGlobalLoading}/>
                {this.genPageTitleUI()}
                {this.genPhoneNumberInputUI()}
                {this.genPasswordInputUI()}
                {this.genForgetPasswordPanelUI()}
                {this.genLoginBtn()}
                {this.genRegisterBtn()}
                {this.genAgreementUI()}
            </ScrollView>

        )
    };

    loginEnable = () => {
        //按钮启用
        this.setState({
            loginButton_disabled: false,
            loginButton_bgColor: Constant.loginButton_enable_bgColor,
            loginButtonTxtColor: Constant.loginButton_enable_txtColor,
            loading: false,
        })
    }

    loginDisable = () => {
        //按钮禁用
        this.setState({
            loginButton_disabled: true,
            loginButton_bgColor: Constant.loginButton_disable_bgColor,
            loginButtonTxtColor: Constant.loginButton_disable_txtColor,
            loading: true,
        })
        //this.loadingEasy();
    }

    forgetPassword = () => {
        this.props.navigation.navigate('ForgetPwd');
    }


    //按钮禁用
    onPressSubmit = () => {
        const {dispatch} = this.props;

        Util.showGlobalLoading(this)
        const {username, password} = this.state
        if (Util.isEmpty(username)) {
            //按钮启用
            this.loginEnable();
            Util.hiddenGlobalLoading(this)
            Util.showToast('用户名不得为空');
            return;
        }

        if (Util.isEmpty(password)) {
            this.loginEnable();
            Util.hiddenGlobalLoading(this)
            Util.showToast('密码不得为空');
            return;
        }


        dispatch(userActions.login(username,password))
            .then(res => {
                if (res.returnType.resultCode === '0') {
                    this.loginEnable();
                    Util.hiddenGlobalLoading(this)
                    Util.showToast(res.returnType.resultMessage);
                } else {
                    Util.hiddenGlobalLoading(this)
                    res.pwd = this.state.password;
                    let date = new Date();
                    let time = date.getYear() + '' + date.getMonth() + '' + date.getDate();
                    res.time = time;
                    InitDB.loginDataToDB(res, () => {
                        Util.showToast(res.returnType.resultMessage);
                        const resetAction = NavigationActions.reset({
                            index: 0,
                            actions: [
                                NavigationActions.navigate({routeName: 'Home'})
                            ]
                        })
                        this.props.navigation.dispatch(resetAction)
                    });
                }
            })
            .catch(err => {
                //请求失败
                Util.hiddenGlobalLoading(this)
                this.loginEnable();
                Util.showToast('登陆失败，错误信息:' + err);
            })
    }

}

const styles = StyleSheet.create({
    body: {
        backgroundColor: '#FFF',
        flex: 1,
    },
    header: {
        height: winHeight / 4,
        flex: 1,
        justifyContent: "center",
        alignItems: 'center',
        // backgroundColor:"#cc2828",

    },
    topBg: {
        width: winWidth,
        height: winWidth / 5 * 3,
        //height: 80,
        justifyContent: 'center',
        alignItems: 'center',
        marginBottom: 40,
    },
    loginText: {
        fontSize: 18,
        color: '#FFF',
        position: 'absolute',
        top: 10,
    },
    btn_login: {
        height: 40,
        borderRadius: 8,
        backgroundColor: Color.BTN_BGCOLOR,
        marginRight: 40,
        marginLeft: 40,
        marginTop: 40,
        justifyContent: 'center',
        alignItems: 'center',
    },
    btn_text: {
        fontSize: 15,
        color: Color.BTN_TEXT,
    },
    inputBox: {
        flexDirection: 'row',
        height: 40,
        marginLeft: 40,
        marginRight: 40,
        marginTop: 10,
        borderColor: '#DDD',
        borderRadius: 8,
        borderWidth: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
    icon: {
        height: 15,
        width: 15,
        marginLeft: 10,
        marginRight: 10,
    },
    pwdBox: {
        height: 20,
        marginTop: 10,
        flexDirection: 'row',
        paddingLeft: 5,
        paddingRight: 5,
        marginLeft: 40,
        marginRight: 40,
    },
    hintText: {
        fontSize: 12,
        color: '#999',
        padding: 0,
    },
    inputText: {
        flex: 1,
        marginRight: 10,
    },
});


export default connect((state, props) => {
    return ({
    });
})(LoginScene);